import cgi
import csv
import logging


from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from urlparse import urlparse
import random
from django.utils import simplejson  


class Question(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    author = db.StringProperty()
    url = db.LinkProperty()
    question = db.StringProperty(multiline=True)
    answer = db.StringProperty(multiline=True)
    choices = db.StringListProperty()
    starttime = db.IntegerProperty()
    playtime = db.IntegerProperty()
    desc = db.StringProperty(multiline=True)


class UserInfo(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    name = db.StringProperty(default="")
    uid = db.IntegerProperty(default=0)
    score = db.IntegerProperty(default=0)
    level = db.IntegerProperty(default=1)
    hits = db.IntegerProperty(default=0)
    miss = db.IntegerProperty(default=0)
    currQ = db.IntegerProperty(default=1)


class Get(webapp.RequestHandler):
    def get(self):
        qList = []

        max = self.request.get("max")
        start = self.request.get("start")
        if not max.isdigit():
          max = 10
        if not start.isdigit():
          start = 0;

        max = int(max)
        start = int(start)

        f = open("questions.csv", "r")
        r = csv.DictReader(f)

        logging.info("max=%d start=%d " % (max, start))

        n = 0
        for q in r:

          if int(q['index']) < start:
            continue

          logging.debug("q %s " % q)

          #make strings to ints
          q['points'] = int(q['points'])
          q['playtime'] = int(q['playtime'])
          q['duration'] = int(q['duration'])
          q['starttime'] = int(q['starttime'])
          q['endtime'] = int(q['endtime'])
          q['favorites'] = int(q['favorites'])
          q['hits'] = int(q['hits'])
          q['answer'] = int(q['answer'])
          qList.append(q)

          n = n + 1
          if n >= max:
            break

        #random.shuffle(qList)
        logging.info(qList)
        jsonstr = simplejson.dumps(qList)
        self.response.out.write(jsonstr) 



class UserInfoInterface(webapp.RequestHandler):
    def get(self):

        #get id from request query
        json_arr = {}
        json_arr['uid'] = self.request.get("uid")
        logging.info("in UserInfoInterface get request id %d " % int(json_arr['uid']))

        #fetch the entry from db
        q = db.GqlQuery("SELECT * FROM UserInfo WHERE uid = :1", int(json_arr['uid']))
        r = q.fetch(1)
        logging.debug("in UserInfoInterface get query len %d" % len(r))

        if len(r) == 1:
          ui = r[0]
        else:
          ui = UserInfo()

        #load from db
        json_arr['name'] = ui.name
        json_arr['uid'] = ui.uid
        json_arr['score'] = ui.score
        json_arr['level'] = ui.level
        json_arr['hits'] = ui.hits
        json_arr['miss'] = ui.miss
        json_arr['currQ'] = ui.currQ

        logging.info("in UserInfoInterface get json_arr %s" % json_arr)
        jsonstr = simplejson.dumps(json_arr)
        self.response.out.write(jsonstr) 


    def post(self):

        #get id from posted obj
        json_arr = {}
        json_arr = simplejson.loads(self.request.body)
        logging.info("in UserInfoInterface post request id %d " % int(json_arr['uid']))

        #fetch the entry from db
        q = db.GqlQuery("SELECT * FROM UserInfo WHERE uid = :1", int(json_arr['uid']))
        r = q.fetch(1)
        logging.debug("in UserInfoInterface post query len %d" % len(r))

        if len(r) == 1:
          ui = r[0]
        else:
          ui = UserInfo()

        #save it to the db
        ui.name = json_arr['name']
        ui.uid = int(json_arr['uid'])
        ui.score = int(json_arr['score'])
        ui.level = int(json_arr['level'])
        ui.hits = int(json_arr['hits'])
        ui.miss = int(json_arr['miss'])
        ui.currQ = int(json_arr['currQ'])
        db.put(ui)

        logging.info("in UserInfoInterface post json_arr %s" % json_arr)
        jsonstr = simplejson.dumps(json_arr)
        self.response.out.write(jsonstr) 


application = webapp.WSGIApplication(
                                     [('/get', Get),
                                      ('/userinfo', UserInfoInterface)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
